package com.fiberhome.opticalbox.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.fiberhome.opticalbox.R;
import com.fiberhome.opticalbox.view.third.image.PercentImageView;

public class SpeedCheckingView extends FrameLayout {

	private ImageView imgPointer;
	private PercentImageView imgPercent;
	private TextView txSpeed;

	private static final float TOTAL_ANGLE = 274;
	public static final long DURATION = 1000;
	private float tmpDegress;

	private float[] speedLevel = new float[] { 0, 64, 128, 512, 1024, 5 * 1025, 10 * 1024 };

	public SpeedCheckingView(Context context) {
		this(context, null);
	}

	public SpeedCheckingView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public SpeedCheckingView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater.from(context).inflate(R.layout.ob_view_speed_checking, this);

		imgPointer = (ImageView) findViewById(R.id.img_pointer);
		imgPercent = (PercentImageView) findViewById(R.id.img_percent);
		txSpeed = (TextView) findViewById(R.id.tx_speed);

		reset();
	}

	public void reset() {
		tmpDegress = 0;
		imgPercent.resetCurrAngle();
		txSpeed.setTextColor(0xffffffff);
		txSpeed.setVisibility(View.GONE);
	}

	public void progress(float speed) {
		float progress = computeProgress(speed);

		RotateAnimation rotate = new RotateAnimation(tmpDegress, progress * 0.01f * TOTAL_ANGLE, Animation.RELATIVE_TO_SELF, 0.5f,
				Animation.RELATIVE_TO_SELF, 0.5f);
		rotate.setDuration(DURATION);
		rotate.setFillAfter(true);
		imgPointer.startAnimation(rotate);

		tmpDegress = progress * 0.01f * TOTAL_ANGLE;

		imgPercent.setCurrentPercentByAnim(progress);

		txSpeed.setVisibility(View.VISIBLE);
		if (speed < 1024) {
			txSpeed.setText(String.valueOf((int) speed) + "Kb/s");
		} else {
			txSpeed.setText(String.format("%.2f", speed / 1024) + "Mb/s");
		}
	}

	public void setSpeedInfoTextColor(int color) {
		txSpeed.setTextColor(color);
	}

	private float computeProgress(float speed) {
		if (speed < 0 || speedLevel.length < 1) {
			return 0;
		}
		if (speed < speedLevel[0]) {
			return speedLevel[0];
		}

		float piecePercent = 100 / (float) (speedLevel.length - 1);
		for (int i = 0; i < speedLevel.length; i++) {
			if (speed < speedLevel[i]) {
				return piecePercent * (i - (speedLevel[i] - speed) / (speedLevel[i] - speedLevel[i - 1]));
			}
		}
		return speedLevel[speedLevel.length - 1];
	}
}
